<?php
/**
 * Created by PhpStorm.
 * User: Egg
 * Date: 2018/3/8
 * Time: 13:27
 */

namespace Wechat\Controller;


class HttpUtilController
{
    /**
     * 获取access_token
     * access_token 缓存在session内 7000s获取一次
     * @return string
     */
    public static function getAccessToken()
    {
        // 判断access_token是否存在session中
        if (session('?access_token')) {
            // access_token存在
            // 判断access_token是否过期
            if (time() - session('access_token_time') < 7000) {
                // 未过期直接从session中取
                return session('access_token');
            }
        }
        /**
         *  请求微信获取AccessToken
         *  拼接get字符串
         */
        $url = C('url_access_token')
            . C('appid') . '&secret=' . C('appsecret');

        $result = HttpUtilController::httpGet($url);

        $obj = json_decode($result);
        //判断请求是否成功
        if (array_key_exists($result, 'errcode') && $result['errcode'] == 0) {
            //请求失败
            return '';
        } else {
            /**
             * 缓存 access_token，expires_in(有效时间)
             */
            session('access_token', $obj->access_token);
            session('expires_in', $obj->expires_in);
            session('access_token_time', time());
            return $obj->access_token;
        }
    }

    /**
     * post请求
     * @param $url          请求地址
     * @param null $data    请求数据(json)
     * @return mixed
     *curl请求接口的post方法
     */
    static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /***
     * get请求
     * @param $url          请求地址
     * @return mixed
     */
    public static function httpGet($url)
    {
        //1.初始化
        $curl = curl_init();
        //配置curl
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //执行curl
        $res = curl_exec($curl);
        //关闭curl
        curl_close($curl);
        return $res;
    }
}